import 'package:flutter/material.dart';
import 'package:kiomax/pages/dialog/src_code_dialog.dart';
import 'package:kiomax/pages/location/location_create_page.dart';
import 'package:kiomax/widgets/room/room_item.dart';
import '../../config/string_config.dart';
import '../../config/color_config.dart';
import '../../models/room_info.dart';
import '../../utils/common_util.dart';
import '../../utils/qr_code_parser.dart';
import '../../utils/screen_util.dart';
import '../../widgets/menu/app_drawer.dart';
import '../../widgets/select/dropdown_select.dart';
import '../../widgets/title/page_tip_widget.dart';
import '../../widgets/title/title_widget.dart';
import '../qrcode/qr_code_scanner_page.dart';
import '../room/room_create_page.dart';

class LocationListPage extends StatefulWidget {
  const LocationListPage({Key? key}) : super(key: key);

  @override
  State<LocationListPage> createState() => _LocationListPageState();
}

class _LocationListPageState extends State<LocationListPage> {
  late List<RoomInfo> roomList;
  late List<DropdownSelectItem> locationItems;
  late BuildContext pageContext;
  @override
  void initState() {
    super.initState();
    roomList = [
      RoomInfo(
          id: "1",
          name: "name1",
          machineCount: 3,
          kioskCount: 4,
          modemCount: 1),
      RoomInfo(
          id: "2",
          name: "name2",
          machineCount: 3,
          kioskCount: 4,
          modemCount: 1),
      RoomInfo(
          id: "3",
          name: "name3",
          machineCount: 3,
          kioskCount: 4,
          modemCount: 1),
      RoomInfo(
          id: "4",
          name: "name4",
          machineCount: 3,
          kioskCount: 4,
          modemCount: 1),
      RoomInfo(
          id: "4",
          name: "name4",
          machineCount: 3,
          kioskCount: 4,
          modemCount: 1),
      RoomInfo(
          id: "4",
          name: "name4",
          machineCount: 3,
          kioskCount: 4,
          modemCount: 1),
      RoomInfo(
          id: "4",
          name: "name4",
          machineCount: 3,
          kioskCount: 4,
          modemCount: 1),
      RoomInfo(
          id: "4",
          name: "name4",
          machineCount: 3,
          kioskCount: 4,
          modemCount: 1),
      RoomInfo(
          id: "4",
          name: "name4",
          machineCount: 3,
          kioskCount: 4,
          modemCount: 1),
      RoomInfo(
          id: "4",
          name: "name4",
          machineCount: 3,
          kioskCount: 4,
          modemCount: 1),
      RoomInfo(
          id: "4",
          name: "name4",
          machineCount: 3,
          kioskCount: 4,
          modemCount: 1),
      RoomInfo(
          id: "4",
          name: "name4",
          machineCount: 3,
          kioskCount: 4,
          modemCount: 1),
      RoomInfo(
          id: "4",
          name: "name4",
          machineCount: 3,
          kioskCount: 4,
          modemCount: 1),
      RoomInfo(
          id: "4",
          name: "name4",
          machineCount: 3,
          kioskCount: 4,
          modemCount: 1),
      RoomInfo(
          id: "4",
          name: "name4",
          machineCount: 3,
          kioskCount: 4,
          modemCount: 1),
      RoomInfo(
          id: "4",
          name: "name4",
          machineCount: 3,
          kioskCount: 4,
          modemCount: 1),
      RoomInfo(
          id: "4",
          name: "name4",
          machineCount: 3,
          kioskCount: 4,
          modemCount: 1),
      RoomInfo(
          id: "4",
          name: "name4",
          machineCount: 3,
          kioskCount: 4,
          modemCount: 1),
      RoomInfo(
          id: "4",
          name: "name4",
          machineCount: 3,
          kioskCount: 4,
          modemCount: 1),
      RoomInfo(
          id: "4",
          name: "name4",
          machineCount: 3,
          kioskCount: 4,
          modemCount: 1),
      RoomInfo(
          id: "4",
          name: "name4",
          machineCount: 3,
          kioskCount: 4,
          modemCount: 1),
      RoomInfo(
          id: "4",
          name: "name4",
          machineCount: 3,
          kioskCount: 4,
          modemCount: 1),
      RoomInfo(
          id: "4",
          name: "name4",
          machineCount: 3,
          kioskCount: 4,
          modemCount: 1),
      RoomInfo(
          id: "4",
          name: "name4",
          machineCount: 3,
          kioskCount: 4,
          modemCount: 1),
      RoomInfo(
          id: "4",
          name: "name4",
          machineCount: 3,
          kioskCount: 4,
          modemCount: 1),
      RoomInfo(
          id: "4",
          name: "name4",
          machineCount: 3,
          kioskCount: 4,
          modemCount: 1),
      RoomInfo(
          id: "4",
          name: "name4",
          machineCount: 3,
          kioskCount: 4,
          modemCount: 1),
      RoomInfo(
          id: "4",
          name: "name4",
          machineCount: 3,
          kioskCount: 4,
          modemCount: 1),
    ];
    locationItems = [
      DropdownSelectItem(
        title: StringConfig.create_new_location,
        icon: Icons.add,
        onTap: () {
          // 实现创建新位置的逻辑
          Navigator.push(context, MaterialPageRoute( builder: (context) => const LocationCreatePage(),
          ));
        },
      ),
      DropdownSelectItem(
        title: StringConfig.auto_detect_location,
        icon: Icons.my_location,
        onTap: () => _showAutoDetectDialog(),
      ),
      DropdownSelectItem(
        // 实现扫描位置二维码的逻辑
        title: StringConfig.scan_location_qr,
        icon: Icons.qr_code_scanner,
        onTap: () => startScanQRCode(),
      ),
      DropdownSelectItem(
        title: StringConfig.enter_location_id,
        icon: Icons.edit,
        onTap: () {
          // 实现输入位置ID的逻辑
          _showLocationIdDialog();
        },
      ),
      DropdownSelectItem(title: 'AreenView Arcade'),
      DropdownSelectItem(title: 'Arcade 2'),
      DropdownSelectItem(title: 'Arcade 3'),
    ];
  }

  DropdownSelectItem? selectedLocation;
  DropdownSelectItem? selectedRoom;
  final TextEditingController _locationSearchController =
      TextEditingController();
  final TextEditingController _roomSearchController = TextEditingController();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  @override
  void dispose() {
    print("销毁了销毁了");
    _locationSearchController.dispose();
    _roomSearchController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    pageContext = context;
    return Scaffold(
      key: _scaffoldKey,
      backgroundColor: Colors.white,
      drawer: const AppDrawer(locationId: '782402'),
      appBar: TitleWidget(context: context, scaffoldKey: _scaffoldKey),
      body: Padding(
        padding: const EdgeInsets.fromLTRB(24, 20, 24, 24),
        child: Stack(
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                PageTipWidget(context: context),
                const SizedBox(height: 20),
                DropdownSelect(
                  label: StringConfig.location,
                  hint: StringConfig.select_location,
                  items: locationItems,
                  value: selectedLocation,
                  onChanged: (item) {
                    setState(() {
                      selectedLocation = item;
                    });
                  },
                  searchController: _locationSearchController,
                  showSearch: true,
                  searchHint: StringConfig.select_location,
                ),
                // SelectTypeWidget(leftTip: "Location", context: context,hintMessage: 'Pre-selected the first one' ),
                const SizedBox(height: 20),
                DropdownSelect(
                  label: StringConfig.rooms,
                  hint: StringConfig.search_rooms,
                  items: const [], // TODO: 根据选择的位置加载房间列表
                  value: selectedRoom,
                  onChanged: (item) {
                    setState(() {
                      selectedRoom = item;
                    });
                  },
                  searchController: _roomSearchController,
                  showSearch: true,
                  searchHint: StringConfig.search_rooms,
                ),
                const SizedBox(height: 20),
                Expanded(
                  child: _getRoomList(context),
                )
              ],
            ),
            Positioned(
              bottom: ScreenUtil.setHeight(30),
              right: ScreenUtil.setWidth(20),
              child: SizedBox(
                width: ScreenUtil.designWidth * 0.3,
                height: ScreenUtil.setHeight(50),
                child: ElevatedButton(
                  onPressed: selectedLocation != null
                      ? () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => const RoomCreatePage(),
                            ),
                          );
                        }
                      : null,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: ColorConfig.buttonEnabled,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(100),
                    ),
                    elevation: 0,
                    disabledBackgroundColor: ColorConfig.buttonDisabled,
                  ),
                  child: const Text(
                    StringConfig.Confirm,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget _getRoomList(BuildContext context) {
    return ListView.builder(
      physics: const AlwaysScrollableScrollPhysics(),
      itemBuilder: (context, i) {
        // var index = widget.dataList!.length - i ;
        return InkWell(
          child: Card(
            elevation: 3,
            shape: const RoundedRectangleBorder(
                borderRadius: BorderRadius.all(Radius.circular(10))),
            color: Color(0xFFFFFFFF),
            child: RoomItem(
                roomName: roomList[i].name,
                machineCount: roomList[i].machineCount,
                kioskCount: roomList[i].kioskCount,
                modemCount: roomList[i].modemCount),
          ),
        );
      },
      itemCount: roomList.length,
    );
  }

  // 启动二维码扫描
  Future<void> startScanQRCode() async {
    print('启动二维码扫描');
    try {
      final result = await Navigator.push<dynamic>(
        pageContext,
        MaterialPageRoute(
          builder: (pageContext) => const QRCodeScannerPage(),
        ),
      );
      if (result != null) {
        var qrCode = await QRCodeParser.parseQRCode(result);
        if (!qrCode.isValid) {
          CommonUtil.showTipDialog(pageContext,
              title: qrCode.errorTitle!, message: qrCode.errorMessage!);
        }
      }
    } catch (e) {
      print('Error in QR code scanning: $e');
    }
  }

  // 显示自动检测对话框
  Future<void> _showAutoDetectDialog() async {
    if (!mounted) return;
    print('显示自动检测对话框');
    CommonUtil.showTipDialog(pageContext,
        title: StringConfig.auto_detect_title,
        message: StringConfig.auto_detect_message);
  }

  // 显示location id输入对话框
  Future<void> _showLocationIdDialog() async {
    if (!mounted) return;
    print('显示location id输入对话框');
    try {
      final result = await showDialog<String>(
        context: pageContext,
        useRootNavigator: true,
        barrierDismissible: true,
        builder: (BuildContext dialogContext) => WillPopScope(
          onWillPop: () async {
            return true;
          },
          child: const SrcCodeDialog(),
        ),
      );

      if (result != null && mounted) {
        print('输入的location id: $result');
      }
    } catch (e) {
      print('显示location id对话框错误: $e');
    }
  }
}
